$(function() {

  var people = {};
  var groups = {};
  var markers = [];
  var checkins;
  var waiting_for_people;
  var markers_by_place = {};
  var last_infowindow;
  
  
  function people_ready() {
    for (var i in groups) {
      if (groups.hasOwnProperty(i)) {
        group_checkins = groups[i];

        var icon = 'female';
        var checkin;
        
    //    console.log('delka '+group_checkins.length);
        if(group_checkins.length > 1) {
          icon = 'group'
        } else {
          checkin = group_checkins[0];
          //if (people[checkin.from.id]!=undefined) {
            icon = people[checkin.from.id].sex ;
          //}
        }
        

        var persons = [];
        for( var x in group_checkins) {
          checkin = group_checkins[x];
          if(people[checkin.from.id]!=undefined) {
            persons[x] = people[checkin.from.id];
          }
        }
        
        var pos = new google.maps.LatLng(checkin.place.location.latitude, checkin.place.location.longitude);

        markers[i] = new google.maps.Marker({
          position: pos,
          map: map,
          title:checkin.from.name,
          clickable:true,
          icon:'/img/'+icon+'.png',
        });
        markers_by_place[checkin.place.id] = markers[i];



        
        google.maps.event.addListener(markers[i], 'click', function(persons, i) {
          return function() {
            var template = $('#info_window_tmpl').html();
            var content = '';
            for(var x in persons) {
              console.log(people[persons[x].id])
              content += $.mustache(template, persons[x]);
            }
            

            // open only one window
            if (last_infowindow) {
              console.log('yessss');
              last_infowindow.close();
            }
            
            // open new one
            var infoWindow = new google.maps.InfoWindow({
              content: content
            });
            infoWindow.open(map, markers[i]);
            
            // last opened
            last_infowindow = infoWindow;
            console.log('last infoWindow', last_infowindow);

          }
        }(persons, i));
      }
    }
  };
  
  
  
  var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
  var map = new google.maps.Map(document.getElementById("map_canvas"), {
    zoom: 8,
    //center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  var handleError = function(error) {
    alert(error);
  };

  var e = function(html) {
    var el = document.createElement('div');
    el.innerHTML = html;
    return el.children[0];
  };
  
  var prepair_data = function() {
    console.log('prepair data');
    waiting_for_people = 0;
    var find_people = [];
    for (var i = 0; i < checkins.length; i++) {
      var checkin = checkins[i];
      if (!groups[checkin.place.id]) {
        groups[checkin.place.id] = [];
      }
      groups[checkin.place.id].push(checkin);
      find_people.push(checkin.from.id);
      waiting_for_people++;
    }
    for (var i = 0; i < find_people.length; i++) {
      var id = find_people[i];
      var q = FB.Data.query('select name, sex, pic_square from user where uid={0}', id);
      q.wait(function(id) {
        return function(rows) {
          var result = rows[0];
          console.log('PERSON '+id, result);
          people[id] = {
            name: result.name,
            pic: result.pic_square,
            sex: result.sex
          };
          console.log(waiting_for_people);
          waiting_for_people--;
          if (waiting_for_people === 0) {
            $('body').trigger('people_ready');
            people_ready();
          }
        };
      }(id));
    }
  };

  $('body').bind('people_ready', function() {
    var list = document.getElementById('list');
    for (var g in groups) {
      if (groups.hasOwnProperty(g)) {
        group_checkins = groups[g];
        var group = list.appendChild(e('<div class="checkin_group"></div>'));
        group.appendChild(e('<div class="place" onclick="show_group('+g+')">'+group_checkins[0].place.name+'</div>'));
        for (var i = 0; i < group_checkins.length; i++) {
          render_checkin(group_checkins[i], group);
        }
        group.appendChild(e('<div class="clear"></div>'));
      }
    }
  });
  
  window.show_group = function(g) {
    var group = groups[g];
    var checkin = group[0];
    
    var new_position = new google.maps.LatLng(checkin.place.location.latitude, checkin.place.location.longitude);
    map.panTo(new_position);
    var marker = markers_by_place[checkin.place.id];
    google.maps.event.trigger(marker, 'click');
  };

  var render_checkin = function(checkin, root) {
    console.log(checkin.from.id);
    var person = people[checkin.from.id];
    var checkin_el = e('<div class="checkin"></div>');
    checkin_el.appendChild(e('<div class="avatar"><img src="'+person.pic+'"/></div>'));
    checkin_el.appendChild(e('<div class="name">'+person.name+'</div>'));
    checkin_el.appendChild(e('<div class="sex">'+person.sex+'</div>'));
    root.appendChild(checkin_el);
  };

  
  function placesResponseHandler(response) {
  /*
    console.log('placesResponseHandler');
    var latlngs = [],
    markers = [];
    var infowindows = [];

    for (var i = 0; i < response.data.length; i++) {
      var checkin = response.data[i];
      // latlng = new CM.LatLng(checkin.place.location.latitude, checkin.place.location.longitude);
      //console.log('Geo: ', checkin.place.location.latitude, checkin.place.location.longitude);

      console.log(checkin);

      var pos = new google.maps.LatLng(checkin.place.location.latitude, checkin.place.location.longitude);
      markers[i] = new google.maps.Marker({
        position: pos,
        map: map,
        title:checkin.from.name,
        clickable:true
      });

      // $.mustache($('info_window_tmpl').html(), data);
      console.debug('From: ', checkin.from);

      var from_person = checkin.from;
      google.maps.event.addListener(markers[i], 'click', function(from_person, i) {
        return function() {
          var template = $('#info_window_tmpl').html();
          var content = $.mustache(template, people[from_person.id]);

          var infoWindow = new google.maps.InfoWindow({
            content: content
          }).open(map, markers[i]);

        }
      }(from_person, i));
    }
    */
    checkins = response.data;
    prepair_data();
  }

  var search_friends = function(success) {
    console.log('search friends');
    FB.api('/search?type=checkin&access_token=' + localStorage.getItem("fb_token"), function(response) {
      console.log('search friends response ',response);
      if (response.error) {
        localStorage.removeItem('fb_token');
      } else {
        if (success) {
          success();
        }
        placesResponseHandler(response);
      }
    });
  };

  var loginHandler = function(response) {
    if (response.session) {
      localStorage.setItem("fb_token", response.session.access_token);
      search_friends(function() {
        document.getElementById('login').innerHTML = 'Logged in.';
      });
    } else {
      alert("Login was not successful, please try again.");
    }
  };

  FB.Event.subscribe('auth.sessionChange', loginHandler);
  FB.init({appId: '186977921348950', xfbml: true});

  if (localStorage.getItem("fb_token")) {
    search_friends(function() {
        document.getElementById('login').innerHTML = 'Logged in.';
      });
  }

  function inspect(obj) {
    var str = '<ul>';
    for (var i in obj) {
      str += '<li>' + i + ': ' + (typeof obj[i] == 'object' ? inspect(obj[i]) : obj[i]) + '</li>';
    }
    return str + '</ul>';
  }

  if (!navigator.geolocation) {
    alert("Can't do this!");
    return;
  }

  navigator.geolocation.getCurrentPosition(function(position) {
    var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

    map.setCenter(pos);
    //map.addOverlay(new GMarker(here.pos));

    var marker = new google.maps.Marker({
      position: pos,
      map: map,
      title:"Hello World!"
    });
    

    //geocoder.getLocations(here.pos, findNearbyJobs);
    },handleError);


  $.mustache = function(template, view, partials) {
    return Mustache.to_html(template, view, partials);
  };

});
